package com.jinlejia.erp.ui.message;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.MessageDetailsAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.FragmentFavoritesBinding;
import com.jinlejia.erp.utils.DataFilter;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 收藏信息（Fragment）
 */

public class FavoritesMessageFragment extends Fragment implements YfLoadMoreListener,SwipeRefreshLayout.OnRefreshListener {
    private MessageDetailsAdapter adapter;
    private View view;
    private String type,time;
    private JSONObject jsonObject = new JSONObject();
    private int page = 1;
    private boolean mLoadingLock = false;
    private ArrayList<Map<String, Object>> dataList = new ArrayList<>();

    public FavoritesMessageFragment() {

    }

    public static FavoritesMessageFragment newInstance(String serviceType,String time) {
        FavoritesMessageFragment fragment = new FavoritesMessageFragment();
        Bundle args = new Bundle();
        args.putString("serviceType", serviceType);
        args.putString("time", time);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            type = getArguments().getString("serviceType");
            time = getArguments().getString("time");
        }
    }

    private FragmentFavoritesBinding binding;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (view == null) {
            EventBus.getDefault().register(this);
            view = inflater.inflate(R.layout.fragment_favorites, null);
            binding = DataBindingUtil.bind(view);
            initView();
        }
        // 缓存的rootView需要判断是否已经被加过parent，
        // 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        binding = DataBindingUtil.bind(view);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        page = 1;
        getData();
    }

    /**
     * 初始化视图
     */
    private void initView() {

        binding.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.refreshLayout.setOnRefreshListener(this);

        binding.recyclerView.setHasFixedSize(true);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.recyclerView.enableAutoLoadMore(this);

        adapter = new MessageDetailsAdapter(dataList);
        adapter.changeMode(YfListMode.MODE_LOADING);
        binding.recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener((view, o) -> {
            Intent intent = new Intent(getActivity(), MessageContentActivity.class);
            intent.putExtra("objectId", ((Map<String, Object>) o).get("objectId").toString());
            intent.putExtra("time",time);
            startActivity(intent);
        });
    }


    /**
     * 获取数据
     */
    private void getData() {
        mLoadingLock = true;
        jsonObject.put("pageSize", 10);
        jsonObject.put("page", page);
        jsonObject.put("serviceType", type);
        jsonObject.put("remindType", time);
        jsonObject.put("type", "collect");
        OkHttpUtils
                .postString()
                .url(ApiConfig.MESSAGE_LIST_ALL)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(getActivity(), response, adapter)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            //数据列表
                            ArrayList<Map<String, Object>> list = JSON.parseObject(data.getJSONArray("allList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (page == 1) {
                                adapter.setData(list);
                            } else {
                                adapter.addData(list);
                            }
                        }
                        if (binding.refreshLayout.isRefreshing()) {
                            binding.refreshLayout.setRefreshing(false);
                        }
                        mLoadingLock = false;
                    }
                });
    }


    @Override
    public void loadMore() {
        if (adapter.getData().size() % 10 == 0) {
            if (mLoadingLock) {
                return;
            }
            mLoadingLock = true;
            page++;
            adapter.addFooter("loading");

            getData();
        }else if( adapter.getData().size() > 10 ){
            adapter.addFooter(R.string.is_all);
        }
    }

    @Subscriber(tag = "TAG_ISCOLLECT_MESSAGE")
    public void refresh() {
        getData();
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onRefresh() {
        getData();
    }
}
